// src/main/java/tech/aistar/controller/OrderController.java
package tech.aistar.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import tech.aistar.pojo.Order;
import tech.aistar.service.OrderService;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/admin/orders")
public class OrderController {

    @Autowired
    private OrderService orderService;

    /**
     * 获取订单列表（分页+搜索）
     * GET /api/admin/orders?orderId=xxx&buyerName=xxx&orderStatus=1&page=1&size=10
     */
    @GetMapping
    public Map<String, Object> getOrderList(
            @RequestParam(required = false) String orderId,
            @RequestParam(required = false) String buyerName,
            @RequestParam(required = false) Integer orderStatus,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {

        List<Order> orders = orderService.getOrderList(orderId, buyerName, orderStatus, page, size);
        Long total = orderService.getOrderCount(orderId, buyerName, orderStatus);

        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("data", orders);
        result.put("total", total);
        result.put("page", page);
        result.put("size", size);
        return result;
    }

    /**
     * 获取订单详情
     * GET /api/admin/orders/{orderId}
     */
    @GetMapping("/{orderId}")
    public Map<String, Object> getOrderDetail(@PathVariable String orderId) {
        Order order = orderService.getOrderById(orderId);
        Map<String, Object> result = new HashMap<>();
        if (order != null) {
            result.put("success", true);
            result.put("data", order);
        } else {
            result.put("success", false);
            result.put("message", "订单不存在");
        }
        return result;
    }

    /**
     * 取消订单并退款
     * PUT /api/admin/orders/{orderId}/cancel
     */
    @PutMapping("/{orderId}/cancel")
    public Map<String, Object> cancelOrder(@PathVariable String orderId) {
        boolean success = orderService.cancelOrder(orderId);
        Map<String, Object> result = new HashMap<>();
        result.put("success", success);
        result.put("message", success ? "订单取消成功，已退款给买家" : "订单取消失败");
        return result;
    }

    /**
     * 完成订单（自动打款给卖家）
     * PUT /api/admin/orders/{orderId}/complete
     */
    @PutMapping("/{orderId}/complete")
    public Map<String, Object> completeOrder(@PathVariable String orderId) {
        boolean success = orderService.completeOrder(orderId);
        Map<String, Object> result = new HashMap<>();
        result.put("success", success);
        result.put("message", success ? "订单完成，已打款给卖家" : "订单完成失败");
        return result;
    }
}